package com.lanlian.cayman.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.lanlian.cayman.R;
import com.lanlian.cayman.adapter.UploadAdapter;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.ReqQueryUpload;
import com.lanlian.commonlib.bean.ReqUpload;
import com.lanlian.commonlib.bean.RespUploadData;
import com.lanlian.commonlib.bean.UploadDataInfo;
import com.lanlian.commonlib.common.SystemConfig;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.upyun.IUploadFileCallback;
import com.lanlian.commonlib.upyun.MUploadFile;
import com.lanlian.commonlib.upyun.UploadPic;
import com.lanlian.uikit.ActionItem;
import com.lanlian.uikit.CustomBottomSheetDialog;
import com.lanlian.utillib.CommonUtils;
import com.lanlian.utillib.DateUtils;
import com.lanlian.utillib.ImageUtils;

import java.io.File;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/11/6 17:34
 *     desc   : 上传资料页面
 *     version: 1.0
 * </pre>
 */
public class UploadActivity extends BaseActivity implements View.OnClickListener {

    private static final int UPLOAD_SUCCESS = 1;
    private static final int UPLOAD_FAILED = 2;

    private GridView mGridView;
    private GridView mGridView2;
    private TextView mTvUpload;

    private UploadAdapter mAdapter;
    private UploadAdapter mAdapter2;
    private ArrayList<String> mPicList = new ArrayList<>();
    private ArrayList<UploadDataInfo> mUploadDataList = new ArrayList<>();
    private CustomBottomSheetDialog mBottomSheetDialog;
    private ArrayList<MUploadFile> mUploadFileList = new ArrayList<>();
    private String mMobile;

    private MyHandler mHandler = new MyHandler(this);
    private boolean mUploadSuccess;

    private static class MyHandler extends Handler {

        private final WeakReference<UploadActivity> mActivity;

        MyHandler(UploadActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message message) {
            UploadActivity activity = mActivity.get();
            if (activity != null) {
                if (message.what == UPLOAD_SUCCESS) {
                    activity.uploadToServer();
                } else if (message.what == UPLOAD_FAILED) {
                    activity.dismissLoadingDialog();
                    activity.mTvUpload.setClickable(true);
                    activity.showToast("提交失败，请再次尝试");
                }
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload, true);
        initData();
        initView();
        setListeners();
        mBottomSheetDialog = new CustomBottomSheetDialog(this, "请选择");
        mBottomSheetDialog.addAction(new ActionItem("拍照"));
        mBottomSheetDialog.addAction(new ActionItem("从相册中选取"));
        mBottomSheetDialog.setOnItemClickListener(new CustomBottomSheetDialog.OnItemOnClickListener() {
            @Override
            public void onItemClick(ActionItem item, int position) {
                switch (item.mTitle) {
                    case "拍照":
                        openSysCamera();
                        break;
                    case "从相册中选取":
                        openSysAlbum();
                        break;
                    default:
                        break;
                }
            }
        });
        mAdapter = new UploadAdapter(this, mPicList);
        mGridView.setAdapter(mAdapter);
        mAdapter2 = new UploadAdapter(mUploadDataList, this);
        mGridView2.setAdapter(mAdapter2);
        getUploadDataList();
    }

    @Override
    protected void initData() {
        super.initData();
        mMobile = getIntent().getStringExtra("mobile");
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("上传资料");
        mTvUpload = findViewById(R.id.tv_upload);
        mGridView = findViewById(R.id.grid_view);
        mGridView2 = findViewById(R.id.grid_view2);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mTvUpload.setOnClickListener(this);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
                if (position == mPicList.size()) {
                    mBottomSheetDialog.showDialog();
                }
            }
        });
    }

    private void getUploadDataList() {
        ReqQueryUpload reqQueryUpload = new ReqQueryUpload();
        reqQueryUpload.setMobileNo(mMobile);
        VolleyRequestUtils.getInstance().queryUploadFile(this.toString(), reqQueryUpload, new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                RespUploadData respUploadData = (RespUploadData) response;
                mUploadDataList.clear();
                mUploadDataList.addAll(respUploadData.getDataList());
                mAdapter2.notifyDataSetChanged();
            }

            @Override
            public void onFail(BaseResponse baseResponse) {
                dismissLoadingDialog();
                showToast(baseResponse.getMsg());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_upload:
                if (CommonUtils.isListEmpty(mPicList)) {
                    showToast("请至少选择一张图片");
                } else {
                    submit();
                }
                break;
            default:
                break;
        }
    }

    private void submit() {
        showLoadingDialog("提交中...");
        if (mUploadSuccess) {
            uploadToServer();
        } else {
            mUploadFileList.clear();
            uploadToUpyun();
        }
    }

    private void uploadToServer() {
        ReqUpload reqUpload = new ReqUpload();
        reqUpload.setMobileNo(mMobile);
        StringBuilder fileUrls = new StringBuilder();
        for (MUploadFile mUploadFile : mUploadFileList) {
            if (mUploadFileList.indexOf(mUploadFile) == mUploadFileList.size() - 1) {
                fileUrls.append(mUploadFile.getUrl());
            } else {
                fileUrls.append(mUploadFile.getUrl()).append(",");
            }
        }
        reqUpload.setFileUrls(fileUrls.toString());
        VolleyRequestUtils.getInstance().uploadFile(this.toString(), reqUpload, new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                dismissLoadingDialog();
                showToast("提交成功");
                finish();
            }

            @Override
            public void onFail(BaseResponse baseResponse) {
                dismissLoadingDialog();
                showToast(baseResponse.getMsg());
            }
        });
    }

    /**
     * 打开系统相机
     */
    private void openSysCamera() {
        File outPutFile = new File(ImageUtils.IMAGE_SAVE_PATH, "output.png");
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", outPutFile);
        } else {
            imageUri = Uri.fromFile(outPutFile);
        }
        //启动相机程序
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, SystemConfig.REQUEST_TAKE_PHOTO);
    }

    /**
     * 打开系统相册
     */
    private void openSysAlbum() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, SystemConfig.REQUEST_GALLERY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case SystemConfig.REQUEST_TAKE_PHOTO:
                    savePic(getImageUri());
                    break;
                case SystemConfig.REQUEST_GALLERY:
                    savePic(data.getData());
                    break;
                default:
                    break;
            }
        }
    }

    private void savePic(Uri imageUri) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            InputStream inputStream = getContentResolver().openInputStream(imageUri);
            BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();
            int height = options.outHeight;
            int width = options.outWidth;
            int sampleSize = 1;
            int max = Math.max(height, width);
            if (max > 769) {
                int nw = width / 2;
                int nh = height / 2;
                while ((nw / sampleSize) > 769 || (nh / sampleSize) > 769) {
                    sampleSize *= 2;
                }
            }
            options.inSampleSize = sampleSize;
            options.inJustDecodeBounds = false;
            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, options);
            String fileName = DateUtils.longToString(System.currentTimeMillis(), "yyyyMMddHHmmssSSS") +
                    (int) ((Math.random() * 9 + 1) * 100);
            String urlPath = ImageUtils.saveBitmap(this, bitmap, fileName + ".jpg");
            mPicList.add(urlPath);
            mAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void uploadToUpyun() {
        for (String picPath : mPicList) {
            UploadPic.uploadFileWithCompress(this, picPath, new IUploadFileCallback() {
                @Override
                public void onProgress(int percent) {
                    Log.e("upload", percent + "");
                }

                @Override
                public void onData(Object output) {
                    if (output != null) {
                        MUploadFile uploadFile = (MUploadFile) output;
                        if (uploadFile.isResult()) {
                            mUploadFileList.add(uploadFile);
                            if (mUploadFileList.size() == mPicList.size()) {
                                mUploadSuccess = true;
                                Message message = mHandler.obtainMessage(UPLOAD_SUCCESS);
                                mHandler.sendMessage(message);
                            }
                        } else {
                            Message message = mHandler.obtainMessage(UPLOAD_FAILED);
                            mHandler.sendMessage(message);
                        }
                    }
                }
            });
        }
    }

    /**
     * 获取图片裁剪Uri
     */
    private Uri getImageUri() {
        File outPutFile = new File(ImageUtils.IMAGE_SAVE_PATH, "output.png");
        Uri imageUri;
        int degree = ImageUtils.readPictureDegree(outPutFile.getPath());
        File file;
        if (degree != 0) {
            String path = ImageUtils.amendRotatePhoto(outPutFile.getPath(), degree, "output.png");
            file = new File(path);
        } else {
            file = outPutFile;
        }
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(this, getPackageName()
                    + ".provider", file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

}
